/**
 * 数据迁移启动脚本
 * 将内存数据库数据迁移到 MongoDB
 */

const { spawn, exec } = require('child_process');
const path = require('path');
const os = require('os');

console.log('🚀 启动数据迁移到 MongoDB...');
console.log('');

// 检测操作系统并使用合适的命令
const isWindows = os.platform() === 'win32';
const migrationScript = path.join(__dirname, 'src/scripts/migrate-to-mongodb.ts');

// 构建命令
let command;
let args;

if (isWindows) {
  // Windows 下直接使用完整路径
  const nodeModulesPath = path.join(__dirname, 'node_modules', '.bin');
  const tsNodePath = path.join(nodeModulesPath, 'ts-node.cmd');
  
  // 检查 ts-node 是否存在
  const fs = require('fs');
  if (fs.existsSync(tsNodePath)) {
    command = tsNodePath;
    args = [migrationScript];
  } else {
    // 降级使用 npx
    command = 'cmd';
    args = ['/c', 'npx', 'ts-node', migrationScript];
  }
} else {
  // Unix/Linux 系统
  command = 'npx';
  args = ['ts-node', migrationScript];
}

console.log(`执行命令: ${command} ${args.join(' ')}`);
console.log('');

const child = spawn(command, args, {
  stdio: 'inherit',
  cwd: __dirname,
  shell: isWindows
});

child.on('close', (code) => {
  if (code === 0) {
    console.log('');
    console.log('🎉 数据迁移完成！');
    console.log('');
    console.log('🔗 可以通过以下 API 验证迁移结果:');
    console.log('  GET http://localhost:8080/v1/mongodb/connection');
    console.log('  GET http://localhost:8080/v1/mongodb/users');
    console.log('  GET http://localhost:8080/v1/mongodb/alerts');
    console.log('  GET http://localhost:8080/v1/mongodb/alert-stats');
  } else {
    console.error(`❌ 迁移失败，退出码: ${code}`);
  }
});

child.on('error', (error) => {
  console.error('❌ 启动迁移脚本失败:', error);
  console.log('');
  console.log('💡 尝试备用方案...');
  
  // 备用方案：直接编译并运行
  console.log('正在编译 TypeScript...');
  exec('npx tsc', { cwd: __dirname }, (compileError) => {
    if (compileError) {
      console.error('❌ TypeScript 编译失败:', compileError);
      console.log('');
      console.log('🔧 请尝试手动运行:');
      console.log('  1. npm run build');
      console.log('  2. node dist/scripts/migrate-to-mongodb.js');
      return;
    }
    
    console.log('✅ 编译成功，运行迁移脚本...');
    const compiledScript = path.join(__dirname, 'dist/scripts/migrate-to-mongodb.js');
    
    const backupChild = spawn('node', [compiledScript], {
      stdio: 'inherit',
      cwd: __dirname
    });
    
    backupChild.on('close', (backupCode) => {
      if (backupCode === 0) {
        console.log('🎉 备用方案执行成功！');
      } else {
        console.error(`❌ 备用方案也失败了，退出码: ${backupCode}`);
      }
    });
  });
});